/* 
 * File:   plyFileReader.cpp
 * Author: walther
 * 
 * Created on October 31, 2012, 7:51 PM
 */

#include "plyFileReader.h"
#include "Scene.h"
#include "Triangle.h"
#include <stdlib.h>
#include <stdio.h>
#include <rply.h>

plyFileReader::plyFileReader(){}



plyFileReader::~plyFileReader(){}



void plyFileReader::loadScene( std::string fileName, Scene* scene )
{
    _scene = scene;
    
    p_ply ply = ply_open( fileName.c_str(), NULL, 0, NULL );
    if (!ply) exit( 1 );
    if (!ply_read_header(ply)) exit( 1 );
    
    long nVertices = ply_set_read_cb(ply, "vertex", "x", vertex_cb, this, 0);
    ply_set_read_cb(ply, "vertex", "y", vertex_cb, this, 0);
    ply_set_read_cb(ply, "vertex", "z", vertex_cb, this, 1);
    
    long nFaces = ply_set_read_cb(ply, "face", "vertex_indices", face_cb, this, 0);
//    printf("%ld\n%ld\n", nVertices, nFaces);
    if (!ply_read(ply)) exit( 1 );
    ply_close(ply);
}



int plyFileReader::vertex_cb(p_ply_argument argument)
{   
    long eol;
    plyFileReader* pThis;
    ply_get_argument_user_data(argument, (void**)&pThis, &eol);
//    printf("%g", ply_get_argument_value(argument));
//    if (eol) printf("\n");
//    else printf(" ");
    
    double value = ply_get_argument_value( argument );
    pThis->_vertices.push_back( value );
    
    return 1;
}



int plyFileReader::face_cb(p_ply_argument argument)
{
    long length, value_index, eol;
    plyFileReader* pThis;
    ply_get_argument_user_data(argument, (void**)&pThis, &eol);
    ply_get_argument_property(argument, NULL, &length, &value_index);
    
    switch (value_index)
    {
        case 0:
        case 1: 
        case 2:
            //printf("%g ", ply_get_argument_value(argument));
            pThis->_faces.push_back( (int)ply_get_argument_value(argument) );
            break;
        default: 
            break;
    }
    return 1;
}




Vector4D plyFileReader::getMin()
{
    _min.x = _vertices[0];
    _min.y = _vertices[1];
    _min.z = _vertices[2];
    
    for (int i = 0; i < _vertices.size(); i+=3)
    {
        if (_vertices[i] < _min.x) _min.x = _vertices[i];
        if (_vertices[i+1] < _min.y) _min.y = _vertices[i+1];
        if (_vertices[i+2] < _min.z) _min.z = _vertices[i+2];
    }
    
    return _min;
}



std::vector<double>& plyFileReader::getVertices()
{
    return _vertices;
}



std::vector<int>& plyFileReader::getFaces()
{
    return _faces;
}
